package com.qf.ability.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.ability.auth.service.SysRoleService;
import com.qf.data.entity.auth.SysRole;
import com.qf.data.entity.auth.SysUserRole;
import com.qf.data.entity.auth.vo.SysRoleVo;
import com.qf.data.mapper.auth.SysRoleDao;
import com.qf.data.mapper.auth.SysUserRoleDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (SysRole)表服务实现类
 *
 * @author makejava
 * @since 2021-10-21 14:26:13
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleDao sysRoleDao;

    @Autowired
    private SysUserRoleDao sysUserRoleDao;


    @Override
    public List<SysRoleVo> queryRolesByUid(Long uid) {
        return sysRoleDao.queryRolesByUid(uid);
    }

    /**
     * 查询当前用户拥有的角色列表
     * @param uid
     * @return
     */
    @Override
    public List<SysRole> queryHasRolesByUid(Long uid) {
        return sysRoleDao.queryHasRolesByUid(uid);
    }

    /**
     * 修改指定用户的角色关系
     * @param uid
     * @param rids
     * @return
     */
    @Override
    @Transactional
    public int updateUserRoles(Long uid, List<Long> rids) {

        //删除当前用户的所有关系
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>(new SysUserRole()).eq("u_id", uid);
        int delete = sysUserRoleDao.delete(queryWrapper);

        //错误：循环插入 查询A表 循环A结果，根据外键查询B表
        //正确：查询A表 -> List<A> -> List<外键> -> 一条SQL -> 所有关联的B表记录

        //添加用户角色关系
//        rids.stream()
//                .map(roid -> new SysUserRole().setUId(uid).setRoId(roid))
//                .forEach(sysUserRole -> {
//                    //保存到数据库
//                    sysUserRoleDao.insert(sysUserRole);
//                });

        if (rids.size() > 0) {
            List<SysUserRole> sysUserRole = rids.stream()
                    .map(roid -> new SysUserRole().setUId(uid).setRoId(roid).setCreateTime(new Date()))
                    .collect(Collectors.toList());
            int result = sysUserRoleDao.insertBatch(sysUserRole);
            return result;
        }
        return -1;
    }
}
